﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MCB.Trading.Generic;

namespace MCB.Trading.Test.Market
{
    public class StandardAlgorithm<TOrderKey, TOrder,TProduct> : 
        IAlgorithm<TOrderKey, TOrder, TProduct> where TOrder : IOrder<TOrderKey, TProduct>
    {
        public virtual MatchedDelegate<TOrderKey, TOrder, TProduct> Matched { get; set; }

        public virtual void Match(OrderBook<TOrderKey, TOrder, TProduct> book, TOrder incomingItem)
        {
            foreach (TOrder bookItem in book)
            {
                if (incomingItem.Id.Equals(bookItem.Id) && incomingItem.Side != bookItem.Side)
                {
                    if (incomingItem.Side == SideEnum.Buy)
                    {
                        if (incomingItem.Volume <= bookItem.Volume && incomingItem.Value <= bookItem.Value)
                        {
                            if (book.BuyTopOfBook == null)
                                book.BuyTopOfBook = bookItem;

                            if (incomingItem.Volume > book.BuyTopOfBook.Volume ||
                                incomingItem.Value > book.BuyTopOfBook.Value)
                            {
                                book.BuyTopOfBook = bookItem;
                            }

                            Matched(book, bookItem);
                        }
                    }
                    else
                    {
                        if (incomingItem.Volume >= bookItem.Volume && incomingItem.Value >= bookItem.Value)
                        {
                            if (book.SellTopOfBook == null)
                                book.SellTopOfBook = bookItem;

                            if (incomingItem.Volume > book.SellTopOfBook.Volume ||
                                incomingItem.Value > book.SellTopOfBook.Value)
                            {
                                book.SellTopOfBook = bookItem;
                            }

                            Matched(book, bookItem);
                        }
                    }
                }
            }
        }
    }
}
